package com.kilomob.grady.handler.netty;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kilomob.grady.model.Request;
import com.kilomob.grady.model.Response;
import com.kilomob.grady.server.netty.NettyServer;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 
 * 消息接受处理类
 * 
 * @author zhouzhixiang
 * @since 1.0
 */
public class MessageReceiveHandler extends ChannelInboundHandlerAdapter {
    private static Logger LOGGER = LoggerFactory.getLogger(MessageReceiveHandler.class);

    private final Map<String, Object> handlerMap;
    private static final String HEARDBEAT_CLASS_NAME = "xxx.xxx.HeardBeat";

    public MessageReceiveHandler(Map<String, Object> handlerMap) {
        this.handlerMap = handlerMap;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            switch (e.state()) {
                case READER_IDLE:
                    LOGGER.debug("5 秒没有接收到客户端的信息了");
                    break;
                case WRITER_IDLE:
                    LOGGER.debug("---WRITER_IDLE---");
                    break;
                case ALL_IDLE:
                    LOGGER.debug("---ALL_IDLE---");
                    break;
                default:
                    break;
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }


    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Request request = (Request) msg;
        if (!request.getClassName().equals(HEARDBEAT_CLASS_NAME)) {
            Response response = new Response();
            String className = request.getClassName();
            Object serviceBean = handlerMap.get(className);
            String methodName = request.getMethodName();
            Object[] parameters = request.getParameters();
            try {
                MessageReceiveInitializeTask recvTask = new MessageReceiveInitializeTask(
                        ctx.channel(), request, response, handlerMap);
                NettyServer.submit(recvTask);
                // Object res = MethodUtils.invokeMethod(serviceBean, methodName, parameters);
                // response.setMessageId(request.getMessageId());
                // response.setResult(res);
                // ctx.writeAndFlush(response);
            } catch (Exception e) {
                LOGGER.error("invoker error:", e);
            }
        } else {
            LOGGER.debug("receiver heardbeat msg!");
        }

    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        LOGGER.error("client may be error:", cause);
    }
}

